<?php
/*****************************************************************
 * Fusion.Board
 *
 * @author                Denis Wrobel
 * @license               http://www.gnu.org/licenses/gpl-3.0.html
 * @version               0.1
 *
 *****************************************************************/

if( !defined( 'IN_SCRIPT' ) )
{
    die( 'Go Away!' );
}


class Cache
{
    /*
     * Save Cache
     * @param string $data Cache data
     * @param string file File to save
     * @param integer $timeout Cache timeout
     */
    public function cacheData( $data, $file, $timeout = 0 )
    {
        $cache_expire = time() + $timeout;
        
        if( !is_array( $data ) )
        {
            $cacheContent = '<?php' . "\n\n";
            $cacheContent .= 'if( !defined( \'IN_CACHE\' ) ) { die( \'Go Away!\' ); }' . "\n";
            $cacheContent .= '$timeout = ' . $cache_expire . ';' . "\n";
            $cacheContent .= '$cache = \'' . addslashes( $data ) . '\';' . "\n";
            $cacheContent .= '?>';
        }
        else
        {
            $parseArray = 'array(' . "\n";
            foreach( $data AS $cache_key => $cache_content )
            {
                $parseArray .= '\'' . addslashes( $cache_key ) . '\' => \'' . addslashes( $cache_content ) . '\',' . "\n";
            }
            
            $parseArray .= ')';
            
            $cacheContent = '<?php' . "\n\n";
            $cacheContent .= 'if( !defined( \'IN_CACHE\' ) ) { die( \'Go Away!\' ); }' . "\n";
            $cacheContent .= '$timeout = ' . $cache_expire . ';' . "\n";
            $cacheContent .= '$cache = ' . $parseArray . ';' . "\n";
            $cacheContent .= '?>';
        }
        
        @file_put_contents( CACHE . $file, $cacheContent  );
    }
    
    public function cacheDestroy( $file )
    {
        if( file_exists( CACHE . $file ) )
        {
            if( !defined( 'IN_CACHE' ) )
            {
                define( 'IN_CACHE', true );
            }
            
            unlink( CACHE . $file );
        }
        else
        {
            return false;
        }
    }
    
    /*
     * Read cache
     * @param string $file Cache file to read
     * @return Cache data
     */
    public function cacheRead( $file )
    {
        if( file_exists( CACHE . $file ) )
        {
            if( !defined( 'IN_CACHE' ) )
            {
                define( 'IN_CACHE', true );
            }
            
            @require_once( CACHE . $file );
            
            return $cache;
        }
        else
        {
            return false;
        }
    }
}